import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import AttachmentPanel from './AttachmentPanel';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const DataForm = ({ id, onCancel, modal, onSubmit, ...formProps }) => {
  const { orderStore: store } = useStore();
  const {
    show,
    record,
    toClose,
  } = modal;

  const [driver] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [editIssue, setEditIssue] = useState(null);

  useEffect(() => { if (toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (id) {
        const res = await store.get(id);
        const comments = await store.getComments({ search: { orderId: res?.id }, pg: { size: 1, page: 0, sort: [] } });
        editCtx.origin = _.cloneDeep(res);
        _.assign(driver, res);
        if (comments?.length > 0) {
          const comment = comments[0];
          _.set(driver, 'auxOrder.auxTask.feedbackInfo.star', comment?.star);
          _.set(driver, 'auxOrder.auxTask.feedbackInfo.evaluateContent', comment?.content);
        }
        store._findDriver(driver, res?.auxOrder?.auxTask?.driverInfos);
      }
    })();
  }, [editIssue]);

  const overrideModel = {
    auxOrder: {
      auxTask: {
        feedbackInfo: {
          attachments: {
            ui: {
              renderer: (v) => {
                return (<AttachmentPanel feedback={driver?.auxOrder?.auxTask.feedbackInfo} mode={'view'} />)
              },
              span: 2,
            },
          },
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCopyItinerary = async () => {
    try {
      const text = await store._copy_itinerary(driver);
      await navigator.clipboard.writeText(text);
      Message.success({ content: t`行程已复制！` });
    } catch (err) {
      console.error('文本复制失败: ', err);
    }
  };

  const handleIntervention = () => {
    setEditIssue({ visible: 'intervention', record });
  };

  const handleCancelEdit = () => {
    setEditIssue(null);
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    onSubmit?.(driver);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      {...formProps}
      value={driver}
      onChange={handleChange}
      inline
      useLabelForErrorMessage
    >
      <TitleGrid title={
        <>
          <span>{t`基本信息`}</span>
          <Button type="secondary" style={{ marginLeft: 20 }} onClick={handleIntervention}>{t`修改接单人`}</Button>
        </>
      }
      />
      <FieldsGrid
        formData={driver}
        mode={show}
        overrideModel={overrideModel}
        fields={[
          'orderNumber', 'auxOrder.groupName', 'price', 'auxOrder.adjustmentPrice', 'auxOrder.orderStatus',
          'auxOrder.publisherName', 'auxOrder.publisherPhone', 'auxOrder.issueOrderPoint', 'crDate',
          'auxOrder.takeName', 'auxOrder.takePhone', 'auxOrder.takeOrderPoint', 'auxOrder.takeOrderTime',
          'auxOrder.content',
        ]}
      />
      <TitleGrid title={(
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {t`行程信息`}
          <Button text type="primary" style={{ marginLeft: 10, fontWeight: 500 }} onClick={handleCopyItinerary}>{t`粘贴行程`}</Button>
        </div>
      )}
      />
      <FieldsGrid
        formData={driver}
        mode={show === 'edit' ? 'edit' : 'view'}
        overrideModel={overrideModel}
        fields={[
          'auxOrder.predictBeginDate', 'auxOrder.onArea',
          'auxOrder.offArea', 'auxOrder.priceType',
          'auxOrder.isRoundTrip', 'auxOrder.eightSeaterFlag',
          'auxOrder.scoreFlag', 'auxOrder.remarks',
        ]}
      />
      <TitleGrid title={t`派车信息`} />
      <FieldsGrid
        formData={driver}
        mode={'view'}
        overrideModel={overrideModel}
        fields={[
          'auxOrder.auxTask.dispatchInformation.name',
          'auxOrder.auxTask.dispatchInformation.contactInformation',
          'auxOrder.auxTask.dispatchInformation.licenseGroup',
          'auxOrder.auxTask.dispatchInformation.dispatchTime',
        ]}
      />
      <TitleGrid title={<span>{t`反馈及评价`}</span>} />
      <FieldsGrid
        formData={driver}
        mode={'view'}
        overrideModel={overrideModel}
        fields={[
          'auxOrder.auxTask.feedbackInfo.content', 'auxOrder.auxTask.feedbackInfo.attachments',
          'auxOrder.auxTask.feedbackInfo.star', 'auxOrder.auxTask.feedbackInfo.evaluateContent',
        ]}
      />
      <TitleGrid title={t`备注信息`} />
      <FieldsGrid
        formData={driver}
        mode={show}
        overrideModel={overrideModel}
        fields={[
          'auxOrder.consoleRemarks',
        ]}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <Intervention modal={editIssue} onCancel={handleCancelEdit} />
    </Form>
  );
};

const Intervention = observer(({ modal, onCancel }) => {
  const { visible, record } = modal || {};
  const { orderStore: store, ruleStore } = useStore();
  const changeRef = useRef();

  useEffect(() => {
    (async () => {
      await store.getMember({ groupIds: [ruleStore._group_id] });
    })();
  }, []);

  const handleOnChange = (v, e, r) => {
    changeRef.current = r;
    if (r && (r.memberId === record?.takeOrderMemberId)) {
      Message.warning({ content: t`当前接单人重复`, duration: 5000 });
    }
  };

  const handleOnSubmit = () => {
    if (!changeRef.current) {
      Message.warning({ content: t`请选择接单人`, duration: 3000 });
      return;
    }
    Dialog.confirm({
      title: t`确认编辑接单人吗？`,
      onOk: async () => {
        try {
          await store.intervention({ orderId: record?.id, member: { ...changeRef.current } });
          Message.success({ content: t`编辑成功` });
        } catch (error) {
          Message.error({ content: t`编辑失败` });
          throw error;
        } finally {
          onCancel?.();
        }
      },
    });
  };

  return (
    <Dialog
      title={t`编辑接单人`}
      visible={visible === 'intervention'}
      style={{ width: 300 }}
      onOk={handleOnSubmit}
      onCancel={onCancel}
      onClose={onCancel}
    >
      <TauSimpleSelect showSearch placeholder={t`请选择接单人`} data={store.members.filter(({ memberId }) => record?.publisherMemberId !== memberId)} onChange={handleOnChange} style={{ width: '100%' }} />
    </Dialog>);
});

export default observer(DataForm);
